import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/http.dart' as http;
import 'package:management/app/api.dart';
import 'package:management/app/cons.dart';
import 'package:management/model/gate_model.dart';
import 'package:management/model/msc_model.dart';
import 'package:management/model/open_gate_record_model.dart';
import 'package:management/utils/convert.dart';
import 'package:management/utils/customTextStyle.dart';
import 'package:management/utils/log_utils.dart';

typedef OnLongPress = void Function(int index);

class GatePageContent extends StatefulWidget {
  final List<GateModel> gateList;
  final OnLongPress onLongPress;

  final VoidCallback onEdit;

  GatePageContent({
    Key? key,
    required this.gateList,
    required this.onLongPress,
    required this.onEdit,
  }) : super(key: key);

  @override
  _GatePageContentState createState() => _GatePageContentState();
}

class _GatePageContentState extends State<GatePageContent> {
  final client = http.Client();
  late List<GateModel> gateList;
  late OnLongPress onLongPress;

  late VoidCallback onEdit;

  @override
  initState() {
    super.initState();
    gateList = widget.gateList;
    onLongPress = widget.onLongPress;
    onEdit = widget.onEdit;
  }

  //登录 => 控制

  @override
  Widget build(BuildContext context) {
    if (widget.gateList == null || gateList.isEmpty) {
      return Center(
        child: Text(
          "还没有添加闸门",
          style: TextStyle(fontSize: 25),
        ),
      );
    }
    return Container(
      padding: EdgeInsets.only(top: 10),
      child: ListView.builder(
        itemBuilder: (context, index) => _buildListItem(context, index),
        itemCount: gateList.length,
      ),
    );
  }

  Widget _buildListItem(BuildContext context, int index) {
    // if (index >= 1) {
    // MyLog.v("index: $index \n "
    //     "gateList: ${gateList[index].mac}  ${gateList[index].deviceName} ${gateList[index].deviceId} ${gateList[index].departmentId} ");
    GateModel gateModel = gateList[index];

    return GatePageItem(
        gateModel: gateModel,
        onLongPress: onLongPress,
        onEdit: onEdit,
        index: index);
    // return ListTile(
    //   //闸门
    //   leading: Icon(Icons.sensor_door),
    //   // subtitle: Text("xxx"),
    //   title: Text(
    //     "畅盈大门${index + 1}",
    //     style: TextStyle(
    //         fontSize: 20, color: Colors.black, fontWeight: FontWeight.bold),
    //   ),
    //   horizontalTitleGap: 80,
    //   trailing: MaterialButton(
    //     minWidth: 100,
    //     height: 68,
    //     color: Colors.yellow,
    //     child: Text(
    //       "开闸",
    //       style: TextStyle(
    //           fontSize: 20, color: Colors.black, fontWeight: FontWeight.bold),
    //     ),
    //     onPressed: () {
    //       loadData();
    //     },
    //   ),
    // );
  }

  ///登录
  @deprecated
  login(String url, String body) async {
    http.Response response = await client.post(Uri.parse(url),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json'
        },
        body: body);
    if (response.statusCode == 200) {
      JsonUtil.getObj(response.body, (v) {
        ParkApi.parkToken = v["data"]["token"];
        ParkApi.parkUserId = v["data"]["id"];
      });
      MyLog.i("""login():
response.body:${response.body}
response.statusCode:${response.statusCode}
userId: ${ParkApi.parkUserId}
token: ${ParkApi.parkToken}""");
    } else {
      MyLog.e("response.statusCode: ${response.statusCode}");
    }
  }

  ///开启畅盈大门
  @deprecated
  openGate() async {
    http.Response response = await client.post(
        Uri.parse(ParkApi.park_host + ParkApi.cyGateOpen),
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'AdminToken': ParkApi.parkToken!
        },
        body: JsonUtil.encodeObj({
          "tcpTokenId": 6741,
          "userId": ParkApi.parkUserId,
          "userName": "btTest"
        }));

    MyLog.i("""openGate():
response.body:${response.body}
userId: ${ParkApi.parkUserId}
token: ${ParkApi.parkToken}
response.statusCode:${response.statusCode}""");
    if (response.statusCode == 401) {
      MyLog.w("response.statusCode:${response.statusCode}");
      http.Response reLogin = await http.post(
          Uri.parse("${ParkApi.park_host}${ParkApi.url_login}"),
          headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
          },
          body: JsonUtil.encodeObj(ParkApi.park_loginBody));
      if (reLogin.statusCode == 200) {
        JsonUtil.getObject(reLogin.body, (v) {
          ParkApi.parkToken = v["data"]["token"];
          ParkApi.parkUserId = v["data"]["id"];
        });
      }
      MyLog.w("reLogin.body:${reLogin.body}");
      MyLog.w("401 重新登录后 token:${ParkApi.parkToken}");
    }
  }

  @deprecated
  loadData() async {
    if (TextUtil.isEmpty(ParkApi.parkToken) && ParkApi.parkUserId == 0) {
      login(ParkApi.park_host + ParkApi.url_login,
          JsonUtil.encodeObj(ParkApi.park_loginBody)!);
      openGate();
    } else {
      openGate();
    }
  }
}

class GatePageItem extends StatefulWidget {
  final GateModel gateModel;
  final OnLongPress onLongPress;
  final VoidCallback onEdit;
  final int index;

  const GatePageItem(
      {Key? key,
      required this.gateModel,
      required this.onLongPress,
      required this.onEdit,
      required this.index})
      : super(key: key);

  @override
  _GatePageItemState createState() => _GatePageItemState();
}

class _GatePageItemState extends State<GatePageItem> {
  String relayName = "assets/images/relay_b.png";
  final GlobalKey<FormState> _globalKey = GlobalKey();
  final TextEditingController _passerbyController = TextEditingController();
  late GateModel gateModel;
  late OnLongPress onLongPress;
  late VoidCallback onEdit;
  late int index;
  Color? textDeviceNameColor = Colors.black;
  Paint? mPaint;

  @override
  void initState() {
    super.initState();
    gateModel = widget.gateModel;
    onLongPress = widget.onLongPress;
    onEdit = widget.onEdit;
    index = widget.index;
  }

  void buildEditDialog(BuildContext context) {
    final TextEditingController deviceNameController = TextEditingController();
    final TextEditingController deviceIDController = TextEditingController();
    final TextEditingController siteIDController = TextEditingController();
    final TextEditingController macController = TextEditingController();
    MyLog.i(gateModel.toMap().toString());
    deviceNameController.text = gateModel.deviceName!;
    deviceIDController.text = gateModel.deviceId!;
    siteIDController.text = gateModel.departmentId!;
    macController.text = gateModel.mac!;
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        content: SingleChildScrollView(
          child: Container(
            width: 500,
            height: 260,
            child: Form(
              key: _globalKey,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Container(
                    height: 60,
                    width: 500,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Container(
                          width: 100,
                          alignment: Alignment.centerRight,
                          child: Text("通道名称："),
                        ),
                        Container(
                          width: 200,
                          child: TextFormField(
                            controller: deviceNameController,
                            validator: _validatorDeviceName,
                            decoration: InputDecoration(
                              hintText: gateModel.deviceName,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    width: 500,
                    height: 60,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Container(
                          width: 100,
                          alignment: Alignment.centerRight,
                          child: Text("设备ID："),
                        ),
                        Container(
                          width: 200,
                          child: TextFormField(
                            controller: deviceIDController,
                            validator: _validatorInterface,
                            decoration:
                                InputDecoration(hintText: gateModel.deviceId),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    width: 500,
                    height: 60,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Container(
                          width: 100,
                          alignment: Alignment.centerRight,
                          child: Text("场地ID："),
                        ),
                        Container(
                          width: 200,
                          child: TextFormField(
                            controller: siteIDController,
                            validator: _validatorInterface,
                            decoration: InputDecoration(
                                hintText: gateModel.departmentId),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Container(
                    height: 60,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Container(
                          width: 100,
                          alignment: Alignment.centerRight,
                          child: Text("MAC地址："),
                        ),
                        Container(
                          width: 200,
                          child: TextFormField(
                            controller: macController,
                            validator: _validatorMac,
                            decoration:
                                InputDecoration(hintText: gateModel.mac),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
        actions: [
          TextButton(
            child: Text("修改"),
            onPressed: () async {
              _globalKey.currentState!.save();
              if (_globalKey.currentState!.validate()) {
                String deviceName = deviceNameController.text;
                String deviceID = deviceIDController.text;
                String mac = macController.text;
                String siteID = siteIDController.text;
                MyLog.i("deviceName: $deviceName \n"
                    "deviceID: $deviceID \n"
                    "departmentID: $siteID \n"
                    "mac: $mac");
                if (deviceName == gateModel.deviceName &&
                    deviceID == gateModel.departmentId &&
                    siteID == gateModel.departmentId &&
                    mac == gateModel.mac) {
                  Navigator.of(context).pop();
                  return;
                }
                await GateProvider.instance.update(
                    GateModel(
                      gateModel.deviceName,
                      gateModel.deviceId,
                      gateModel.departmentId,
                      gateModel.mac,
                    ),
                    GateModel(
                      deviceName,
                      deviceID,
                      siteID,
                      mac,
                    ));
                gateModel.deviceName = deviceName;
                gateModel.deviceId = deviceID;
                gateModel.departmentId = siteID;
                gateModel.mac = mac;
                this.onEdit();
                Navigator.of(context).pop();
              }
            },
          ),
          TextButton(
            child: Text("取消"),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
        ],
      ),
    );
  }

  String? _validatorDeviceName(String? value) {
    if (value!.isEmpty) {
      return "设备名称不能为空";
    }
    return null;
  }

  String? _validatorInterface(String? value) {
    if (value!.isEmpty) {
      return "接口不能为空";
    }
    return null;
  }

  String? _validatorMac(String? value) {
    if (value!.isEmpty) {
      return "MAC地址不能为空";
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(left: 10, right: 10),
      child: Card(
        elevation: 3,
        shadowColor: Colors.red,
        child: InkWell(
          child: Container(
            padding: EdgeInsets.all(10),
            margin: EdgeInsets.only(left: 10, right: 10),
            height: MediaQuery.of(context).size.height * Dimension.hp100,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                // Icon(Icons.camera_front, size: 35),
                relayName == null
                    ? Icon(Icons.camera_front, size: 35)
                    : Image.asset(
                        relayName,
                        height: 35,
                        width: 35,
                      ),
                SizedBox(
                  width: MediaQuery.of(context).size.width * Dimension.wp80,
                ),
                Container(
                  width: MediaQuery.of(context).size.width * Dimension.wp200,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        gateModel.deviceName!,
                        style: TextStyle(
                            fontSize: 25,
                            color: textDeviceNameColor,
                            fontWeight: FontWeight.bold,
                            foreground: mPaint),
                      ),
                      Text(
                        gateModel.mac!,
                        style: TextStyle(fontSize: 20, color: Colors.grey),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  width: MediaQuery.of(context).size.width * Dimension.wp180,
                ),
                Text(
                  "通行人员：",
                  style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                ),
                Container(
                  width: MediaQuery.of(context).size.width * Dimension.wp260,
                  child: TextField(
                    controller: _passerbyController,
                    toolbarOptions: ToolbarOptions(
                        copy: true, cut: true, paste: true, selectAll: true),
                    decoration: InputDecoration(
                      hintText: "请输入通行人员姓名",
                      hintStyle: TextStyle(fontSize: 25),
                      border: OutlineInputBorder(),
                    ),
                  ),
                ),
                SizedBox(
                  width: MediaQuery.of(context).size.width * Dimension.wp800,
                ),
                MaterialButton(
                  minWidth: MediaQuery.of(context).size.width * Dimension.wp160,
                  height: MediaQuery.of(context).size.height * Dimension.hp50,
                  onPressed: () {
                    buildEditDialog(context);
                  },
                  color: Colors.yellow,
                  child: Text(
                    "编辑",
                    style: TextStyle(fontSize: 25, fontWeight: FontWeight.bold),
                  ),
                ),
              ],
            ),
          ),
          onTap: () async {
            String passerby = _passerbyController.text;
            if (TextUtil.isEmpty(passerby)) {
              passerby = "空";
            }

            MyLog.i(
                "gateModel.departmentId：${(gateModel.departmentId) is String} " +
                    gateModel.departmentId!);
            if (int.parse(gateModel.departmentId!) == 0) {
              gateModel.openLPRGate(gateModel.deviceId);
            } else {
              gateModel.openFaceGate(
                  gateRecordModel: GateRecordModel(
                    controlType: 0,
                    gateName: gateModel.deviceName,
                    time: Convert.currentTime(),
                    gateMac: gateModel.mac,
                    operator: SpUtil.getString("userName"),
                    passerby: passerby,
                  ),
                  openGateResultCallback: (openGateResultModel) {
                    if (openGateResultModel.openGate!) {
                      setState(() {
                        relayName = "assets/images/relay_g.png";
                        textDeviceNameColor = null;
                        mPaint = getPaint();
                      });
                      Future.delayed(
                          Duration(milliseconds: 500),
                          () => setState(() {
                                relayName = "assets/images/relay_b.png";
                                mPaint = null;
                                textDeviceNameColor = Colors.black;
                              }));
                    }
                    Map openGateResultMap = openGateResultModel.toMap();
                    MyLog.v("openGateResultModel: $openGateResultMap");
                    final BasicMessageChannel mscChannel = BasicMessageChannel(
                        "MscChannel", StandardMessageCodec());
                    mscChannel.send(MscChannelModel(message: {
                      "cmd": "speak",
                      "data": openGateResultMap
                    }).toMap());
                  });
            }

            _passerbyController.clear();
            _passerbyController.clearComposing();
          },
          onLongPress: () {
            if (this.onLongPress != null) {
              onLongPress(index);
            }
          },
        ),
      ),
    );
  }
}
